package goredis

import (
	"time"

	"github.com/gomodule/redigo/redis"
)

type Options struct {
	Protocol string
	Addr     string
	Password string
	Database int32
}

// 新建redis连接
func New(options *Options) redis.Conn {
	return conn(options)
}

func conn(options *Options) redis.Conn {
	dialOption := redis.DialPassword(options.Password)
	var connect redis.Conn
	if c, err := redis.Dial(options.Protocol, options.Addr, dialOption); err != nil {
		return nil
	} else {
		connect = c
	}
	if _, err := connect.Do("SELECT", options.Database); err != nil {
		return nil
	}
	return connect
}

func NewPool(options *Options) *redis.Pool {
	return pool(options)
}

func pool(options *Options) *redis.Pool {
	return &redis.Pool{
		MaxIdle:     3,
		IdleTimeout: 240 * time.Second,
		Dial: func() (redis.Conn, error) {
			return redis.Dial(options.Protocol, options.Addr, redis.DialPassword(options.Password))
		},
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			_, err := c.Do("PING")
			return err
		},
	}
}
